package com.xzy.shop.web.filter;

import com.xzy.shop.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@WebFilter(urlPatterns = {"/mygxin.html", "/cart.html"})
public class UserFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 得到参数提交方式
        String method = request.getMethod();
        // 分为Get和Post两种方式进行处理
        if (method.equalsIgnoreCase("post")) {
            // post	请求方法，直接可以进行设置
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
        } else {
            // get 请求方法，对于请求的参数的进行改变设置字符集
            response.setContentType("text/html;charset=utf-8");
            Enumeration<String> enumeration = req.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String[] values = request.getParameterValues(key);
                // 对值进行字符集的编码设置
                for (int i = 0; i < values.length; i++) {
                    values[i] = new String(values[i].getBytes("iso-8859-1"), "utf-8");
                }
            }
        }

        PrintWriter out = response.getWriter();

        User user = (User) request.getSession().getAttribute("loginUser");

        if (user == null) {
            out.println("您还未登录，三秒后转跳至登录页面");
            response.setHeader("refresh", "3;/javaweb_shop/index.html");
        } else {
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
